package org.summerframework.core.interceptor;

import org.summerframework.core.util.AnnotationUtils;
import org.summerframework.core.annotation.HtmlRequired;
import org.summerframework.core.annotation.JsonRequired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

/**
 * 拦截器
 * <p>
 * 抽象出获取class、method上的Annotation
 * <p>
 * 获取顺序  method  >  class
 *
 * @author 石超
 * @version v1.0.0
 */
public abstract class AbstractHandlerInterceptorAdapter extends HandlerInterceptorAdapter {
    @Value("${spring.exception.isHtmlRequired}")
    private Boolean isHtmlRequired = false;

    protected <A extends Annotation> A findAnnotation(HandlerMethod handlerMethod, Class<A> aClass) {
        return AnnotationUtils.findAnnotation(handlerMethod, aClass);
    }

    protected boolean hasAnnotation(HandlerMethod handlerMethod, Class<? extends Annotation> aClass) {
        return AnnotationUtils.hasAnnotation(handlerMethod, aClass);
    }

    protected <A extends Annotation> A findAnnotation(Class<?> c, Method method, Class<A> aClass) {
        return AnnotationUtils.findAnnotation(c, method, aClass);
    }

    public void setHtmlRequired(Boolean htmlRequired) {
        isHtmlRequired = htmlRequired;
    }

    protected boolean isHtml(HandlerMethod handlerMethod) {
        boolean isHtml = isHtmlRequired;

        if (hasAnnotation(handlerMethod, HtmlRequired.class)) {
            isHtml = true;
        }

        if ((hasAnnotation(handlerMethod, JsonRequired.class)
                || hasAnnotation(handlerMethod, ResponseBody.class))) {
            isHtml = false;
        }

        return isHtml;
    }
}
